package dai.samples.shiro.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import dai.samples.shiro.entity.Permissions;
import dai.samples.shiro.entity.Role;
import dai.samples.shiro.entity.User;
import dai.samples.shiro.mapper.PermissionsMapper;
import dai.samples.shiro.mapper.RoleMapper;
import dai.samples.shiro.mapper.UserMapper;
import dai.samples.shiro.service.UserService;
import dai.samples.shiro.vo.RoleVo;
import dai.samples.shiro.vo.UserVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户管理接口实现
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    PermissionsMapper permissionsMapper;


    @Override
    public UserVo getUserByName(String loginName) {
        if (StringUtils.isBlank(loginName)) {
            return null;
        }
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("login_name",loginName);
        List<User> users = userMapper.selectList(query);
        if (CollectionUtils.isEmpty(users)) {
            return null;
        }
        User user = users.get(0);
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user,userVo);

        List<Role> roles = roleMapper.getRoleByUserId(user.getUserId());
        List<RoleVo> roleVos = roles.stream().map(item -> {
            RoleVo roleVo = new RoleVo();
            roleVo.setRoleId(item.getRoleId());
            roleVo.setRoleName(item.getRoleName());
            List<Permissions> permissions = permissionsMapper.getPermissionsByRoleId(item.getRoleId());
            roleVo.setPermissions(permissions);
            return roleVo;
        }).collect(Collectors.toList());

        userVo.setRoleVos(roleVos);
        return userVo;
    }

    @Override
    public User getUserById(long userId) {
        User user = userMapper.selectById(userId);
        return user;
    }


}
